package com.jewaton.auth.commons.util;

import org.apache.commons.lang.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil extends org.apache.commons.lang.StringUtils {

	public static String getResetToken() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	/**
	 * 比较前者同后者的差集
	 * 
	 * @param source
	 *            = {“1”，“2”}
	 * @param dest
	 *            = {"2"，“3”}
	 * @return {"1"}
	 */
	public static String[] getMinus(String[] source, String[] dest) {
		int sourceLength = source.length;
		int destLength = dest.length;
		String minusStr = "";
		for (int oPos = 0; oPos < sourceLength; oPos++) {
			String cur = source[oPos];
			boolean flag = true;
			for (int cPos = 0; cPos < destLength; cPos++) {
				String str = dest[cPos];
				if (cur.equals(str)) {
					flag = false;
					break;
				}
			}
			if (flag) {
				minusStr = minusStr + cur + "#";
			}
		}
		if (minusStr.indexOf("#") == -1)
			return new String[] {};
		else
			return minusStr.split("#");
	}

	/**
	 * 以v1#v2#v3#返回
	 * 
	 * @param array
	 * @return
	 */
	public static String getArrayString(String[] array) {
		if (array.length > 0) {
			String arr = "";
			for (int i = 0; i < array.length; i++) {
				arr = arr + array[i] + "#";
			}
			return arr;
		}
		return EMPTY;
	}

	/**
	 * 将字符串数组以v1','v2','v3 的形式返回，数组长度为0则返回空
	 * 
	 * @param array
	 * @return
	 */
	public static String getArray2StrValues(String[] array) {
		if (array.length > 0) {
			String arr = "";
			for (int i = 0; i < array.length; i++) {
				arr = arr + array[i] + "#";
			}
			arr = arr.replace("#", "','");
			return arr;
		}
		return EMPTY;
	}
	
	/**
	 * 将形如v1#v2#v3#的字符串转换为形如v1,v2,v3的字符串，会剔除掉不为数字的子字符串
	 * @param source
	 *            v1#v2#v3#
	 * @return v1,v2,v3 空字符串返回-1000
	 */
	public static String getSQLInValues(String source) {
		String result = "";
		if (isBlank(source)) {
			return "-1000";
		}
		if (source.endsWith("#")) { // fix bug, can not use
									// " source.lastIndexOf("#") != -1 "
			source = source.substring(0, source.length() - 1);
		}
		source = source.replace("#", ",");
		String[] ids = source.split(",");
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < ids.length; i++){
			if (StringUtil.isNumeric(ids[i])){
				list.add(ids[i]);
			}
		}
		for (int i = 0; i < list.size(); i++){
			result = result + list.get(i);
			if (i < (list.size() - 1)){
				result = result + ",";
			}
		}
		return result;
	}

	/**
	 * @param source
	 *            v1#v2#v3#
	 * @return v1','v2','v3 空字符串返回-1000
	 */
	public static String getSQLInStrValues(String source) {
		if (isBlank(source)) {
			return "-1000";
		}
		if (source.endsWith("#")) { // fix bug, can not use
									// " source.lastIndexOf("#") != -1 "
			source = source.substring(0, source.length() - 1);
		}
		source = source.replace("#", "','");
		return source;
	}

	/**
	 * @param source 
	 *            v1#v2#v3#
	 * @return  返回Long类型数组
	 */
	public static Long[] getSQLLongArrayForHql(String source){
		Long[] result = null;
		if(isBlank(source)){
			result = new Long[0];
		}else if (source.endsWith("#")){
			String[] array = source.split("#");
			result = new Long[array.length];
			for (int i = 0; i < array.length; i++){
				if (isNumeric(array[i])){
					result[i] = Long.parseLong(array[i]);
				}else {
					System.err.println("传入的字符串不符合要求！");
					break;
				}
			}
		}
		return result;
	}
	
	/**
	 * @param source 
	 *            v1#v2#v3#
	 * @return  返回Integer类型数组
	 */
	public static Integer[] getSQLIntegerArrayForHql(String source){
		Integer[] result = null;
		if(isBlank(source)){
			result = new Integer[0];
		}else if (source.endsWith("#")){
			String[] array = source.split("#");
			result = new Integer[array.length];
			for (int i = 0; i < array.length; i++){
				if (isNumeric(array[i])){
					result[i] = Integer.parseInt(array[i]);
				}else {
					System.err.println("传入的字符串不符合要求！");
					break;
				}
			}
		}
		return result;
	}
	
	/**
	 * 获取文件后缀名 包括点
	 * 
	 * @param fileName
	 *            abc.jpg
	 * @return .jpg
	 */
	public static String getFileSuffixName(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}

	/**
	 * 生成随机文件名 10位随机数+时间戳+.文件后缀
	 */
	public static String createRandomFileName(String fileName) {
		String randomFileName = getResetToken().substring(0, 10)
				+ DateUtil.getCrurentTimeStamp() + getFileSuffixName(fileName);
		return randomFileName;
	}

	public static void main(String[] args) {

	}

	/**
	 * 判断传入的数组中的元素是否都不为空
	 * @param arry
	 * @return
	 */
	public static boolean isArrayHasNull(String[] arry){
		if (arry.length < 1){
			return false;
		}
		for (int i = 0; i <arry.length; i++){
			if (StringUtil.isBlank(arry[i])){
				return false;
			}
			if (StringUtil.isNotBlank(arry[i]) && i == (arry.length - 1)){
				return true;
			}
		}
		return true;
	}
	
	/**
	 * 传入字符串数组，确保返回数组中每个元素的字符串都不同，可用于多个文件上传时文件名相同的情况
	 * @param name
	 * @return
	 */
	public static String[] makeDiffName(String[] name){
		if (name.length < 1){
			return null;
		}else {
			int count = 1;
			for ( int i = 0; i < name.length; i ++){
				for (int j = 0; j < name.length; j ++){
					if (i == j){
						continue;
					}
					if (name[i].equals(name[j])){
						name[j] = FileNameUtil.getName(name[j]) + "_" + count + "." + FileNameUtil.getExtensionName(name[j]);
						count++;
					}
				}
			}
		}
		return name;
	}
	
	
	
	/**
	 * convert a column number (eg. 1) into an excel column (eg. A)
	 * 
	 * @param columnNumber
	 * @return
	 */
	public static String getExcelColumnName(int columnNumber) {
		int dividend = columnNumber;
		String columnName = "";
		int modulo;
		char temp;
		while (dividend > 0) {
			modulo = (dividend - 1) % 26;
			temp = (char) (65 + modulo);
			columnName = Character.toString(temp) + columnName;
			dividend = (int) ((dividend - modulo) / 26);
		}
		return columnName;
	}

	/**
	 * @param source
	 *            替换null字符串为空 然后trimToNull 主要用于解析xml字符串
	 * @return
	 */
	public static String trimIgnoreNullStr(String source) {
		if (isBlank(source))
			return null;
		return trimToNull(source.replace("null", ""));
	}
	
	/**
	 * 将字符串的值为null转为""
	 * @param str
	 * @return
	 */
	public static String null2Blank(String str){
		return str == null?EMPTY:str;
	}
	
	
	/**
	 * 数据导出excel字符处理
	 * 
	 * @param obj
	 * @return
	 */
	public static String checkDate(Object obj) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		if (null != obj) {
			return format.format(obj);
		} else {
			return "";
		}
	}

	public static String checkData(Object obj) {
		if (null != obj) {
			return obj.toString();
		} else {
			return "";
		}
	}

	/**
	 * 全角转半角
	 * @param input
	 * @return
	 */
	public static String toDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375)
				c[i] = (char) (c[i] - 65248);
		}
		return new String(c);
	}

	/**
	 * 根据传入的网址获取域名
	 * @param url
	 * @return
	 */
	public static String getDomainnameFromUrl(String url){
		//匹配主域
		Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)",Pattern.CASE_INSENSITIVE);
		Matcher matcher = p.matcher(url);
		if (matcher.find()){
			return matcher.group();
		}else {
			if (url.startsWith("http://")){
				url = url.substring(url.indexOf("/")+2);
			}
			if (url.endsWith("/")){
				url = url.substring(0,url.lastIndexOf("/"));
			}
			if (url.contains("/")){
				url = url.substring(0, url.indexOf("/"));
			}
			return url;
		}
	}
	
	/**
	 * 对比两个域名是否相同
	 * @param domain1
	 * @param domain2
	 * @return 相同返回true,不同返回false
	 */
	public static boolean compareDomain(String domain1, String domain2){
		boolean result = false;
		if (StringUtil.isBlank(domain1) || StringUtil.isBlank(domain2)){
			return false;
		}
		if (domain1.equals(domain2)){
			return true;
		}
		if (domain1.contains(domain2) || domain2.contains(domain1)){
			if (domain1.contains("www")){
				domain1 = domain1.substring(domain1.indexOf("www")+4);
				if (domain1.equalsIgnoreCase(domain2)){
					result = true;
				}
			}
			if (domain2.contains("www")){
				domain2 = domain2.substring(domain2.indexOf("www")+4);
				if (domain2.equalsIgnoreCase(domain1)){
					result = true;
				}
			}
		}
		return result;
	}
	
	/**
	 * 返回匹配的分组字符串，不匹配返回null
	 * @param regex 正则表达式
	 * @param str 要匹配的字符串
	 * @param pos 匹配分组位置
	 * @return
	 */
    public static String getMatchStr(String regex, String str, int pos) {
        if (isBlank(regex)) {
            return null;
        }
        Matcher matcher = Pattern.compile(regex).matcher(str);
        if (matcher.find()) {
            return matcher.group(pos);
        } else {
            return null;
        }
    }
    
    /**
     * 返回匹配的分组字符串Map,key为pos，不匹配返回null
     * @param regex 正则表达式
     * @param str 要匹配的字符串
     * @return
     */
    public static Map<String, String> getMatchStrMap(String regex, String str) {
        if (isBlank(regex)) {
            return null;
        }
        Matcher matcher = Pattern.compile(regex).matcher(str);
        if (matcher.find()) {
            Map<String, String> map = new HashMap<String, String>();
            int groupCount = matcher.groupCount();
            for (int i=0; i<=groupCount; i++) {
                map.put(i+"", matcher.group(i));
            }
            return map;
        } else {
            return null;
        }
    }
	
    
    /**
     * 比较两个字符串是否相同,值都为null，视为相同
     * @param str1
     * @param str2
     * @return 相同返回true
     */
    public static boolean compare(String str1, String str2){
    	if (isNotBlank(str1) && isNotBlank(str2)){
    		if (str1.equals(str2) || (" ".equals(str1) && " ".equals(str2))){
    			return true;
    		}else{
    			return false;
    		}
    	}
    	if (isBlank(str1) && isBlank(str2)){
    		return true;
    	}
    	return false;
    }
	
    /**
     * List转字符串数组
     * @param list
     * @return
     */
    public static String[] listToStringArray(List list){
    	String[] array = null;
    	if (list.size() == 0){
    		array = new String[0];
    	}else {
    		int len = list.size();
    		array = new String[len];
    		for (int i = 0; i < len; i++){
    			array[i] = list.get(i).toString();
    		}
    	}
    	return array;
    }
    
    public static int countNumber(String str) {
        int count = 0;
        Pattern p = Pattern.compile("\\d");
        Matcher m = p.matcher(str);
        while(m.find()){
            count++;
        }
        return count;
    }

    public static int countLetter(String str) {
        int count = 0;
        Pattern p = Pattern.compile("[a-zA-Z]");
        Matcher m = p.matcher(str);
        while(m.find()){
            count++;
        }
        return count;
    }

    public static int countChinese(String str) {
        int count = 0;
        Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]");
        Matcher m = p.matcher(str);
        while(m.find()){
            count = count + 2;
        }
        return count;
    }

    /**
     * 统计字符串中数字，字母，中文一共的字符长度并返回此长度
     * @param str
     * @return
     */
    public static Integer countStr(String str){
    	Integer size = countNumber(str) + countLetter(str) + countChinese(str);
    	return size;
    }
    
    /**
     * 统计字符串中数字，字母，中文一共的字符长度，返回指定长度的字符串
     * @param str
     * @return
     */
    public static String countStr(String str, int length){
    	int size = countNumber(str)+countLetter(str)+countChinese(str);
    	if (size < length){
    		return str;
    	}
    	str = str.substring(0,length);
    	size = countNumber(str)+countLetter(str)+countChinese(str);
    	if (size > length){
    		str = countStr(str, length);
    	}
    	return str;
    }
    
    /**
     * 截取字符串指定长度
     * @param s
     * @param length
     * @return
     * @throws Exception
     */
    public static String bSubstring(String s, int length) throws Exception
    {
    	byte[] bytes = s.getBytes("Unicode");
    	if (bytes.length < 2){
    		return s;
    	}
    	int n = 0; // 表示当前的字节数
    	int i = 2; // 要截取的字节数，从第3个字节开始
    	try{
            for (; i < bytes.length && n < length; i++)
            {
                // 奇数位置，如3、5、7等，为UCS2编码中两个字节的第二个字节
                if (i % 2 == 1)
                {
                    n++; // 在UCS2第二个字节时n加1
                }
                else
                {
                    // 当UCS2编码的第一个字节不等于0时，该UCS2字符为汉字，一个汉字算两个字节
                    if (bytes[i] != 0)
                    {
                        n++;
                    }
                }
            }
            // 如果i为奇数时，处理成偶数
            if (i % 2 == 1)
            {
                // 该UCS2字符是汉字时，去掉这个截一半的汉字
                if (bytes[i - 1] != 0)
                    i = i - 1;
                // 该UCS2字符是字母或数字，则保留该字符
                else
                    i = i + 1;
            }
            
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return new String(bytes, 0, i, "Unicode");
    }

    
    
    /**
     * 判断字符串中是否包含另一个字符串，不区分大小写
     * @param str
     * @param beCompare
     * @return
     */
    public static boolean containsIgnoreCase(String str, String beCompare){
    	if (StringUtils.isNotBlank(str) && StringUtil.isNotBlank(beCompare)){
	    	str = upperCase(str);
	    	beCompare = upperCase(beCompare);
	    	return str.contains(beCompare);
    	}else {
    		return false;
    	}
    }
    
    public static boolean isBlankKong(String str) {
        int strLen = str.length();
        if (str == null || strLen == 0) {
            return true;
        }
        return false;
    }
    
}
